<template>
  <el-dialog
    title="选择用户"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="770px"
    :append-to-body="true"
    :before-close="closeDialogHandle"
    @open="openDialog"
    @close="closeDialog"
  >
    <el-container>
      <el-header height="40px">
        <el-form :model="searchUserForm" size="mini" inline @submit.native.prevent>
          <el-form-item label="名称">
            <el-input v-model="searchUserForm.nickName" placeholder="请输入名称"  @keyup.enter.native="queryUsers" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryUsers">查询</el-button>
            <el-button @click="clearSearchForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-alert
        v-if="maxNum > 0"
        :closable="false"
        :title="'提示：最多选择' + maxNum + '位用户'"
        type="info"
      />
      <el-main style="padding: 0 0 10px 0">
        <el-row class="show-selection">
          <el-col :span="4" class="title">当前已选：</el-col>
          <el-col :span="20" class="content">
            <div
              v-for="(item, index) in selection"
              :key="index"
              class="content-item"
            >
              <el-tag
                size="medium"
                @click="removeSelected(item)"
              >
                {{ item[props.label] }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="table"
          v-loading="queryLoading"
          :data="list"
          highlight-current-row
          style="width: 100%"
          @row-click="rowClick"
          @selection-change="selectionChangeHandle"
          @select="selectHandle"
          @select-all="selectAllHandle"
        >
          <el-table-column
            type="selection"
            width="55"
            v-if="multi"
          />
          <el-table-column
            prop="nickName"
            label="名称"
            header-align="center"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="userName"
            label="账户"
            header-align="center"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="remark"
            label="备注"
            header-align="center"
            align="center"
          />
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="searchUserForm.pageNum"
          :limit.sync="searchUserForm.pageSize"
          @pagination="queryUsers"
        />
      </el-main>
      <el-footer height="40px" style="text-align: center">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </el-footer>
    </el-container>
  </el-dialog>
</template>

<script>
import { listUser } from '@/api/system/user'
export default {
  name: 'SelectUserDialog',
  props: {
    show: { type: Boolean, default: false },
    selected: { type: Array, default() { return {} } },
    props: { type: Object, default() { return { label: 'label', value: 'value' } } },
    multi: { type: Boolean, default: true }, // 选择用户数量是否多个
    maxNum: {type: Number, default: 0} // 最多选择几个
  },
  data() {
    return {
      visible: false,
      searchUserForm: {
        pageNum: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      selection: [],
      currentSelected: [],
      selectLoading: false,
      queryLoading: false
    }
  },
  watch: {
    show(val) {
      this.visible = val
    }
  },
  methods: {
    /**
     * 移除已选择
     * @param data
     */
    removeSelected(data) {
      const valueAttr = this.props.value
      const index = this.selection.findIndex(item => item[valueAttr] === data[valueAttr])
      this.selection.splice(index, 1)
      const row = this.list.find(item => item.fid === data[valueAttr])
      if (row) {
        this.$refs.table.toggleRowSelection(row, false)
      }
    },
    /**
     * 确认选择
     */
    confirm() {
      if (this.maxNum > 0 && this.selection.length > this.maxNum) {
        return this.$message({
          message: '最多选择' + this.maxNum + '位用户',
          type: 'error'
        })
      }
      var data = JSON.parse(JSON.stringify(this.selection))
      if (this.visible) {
        this.$emit('select', data)
        setTimeout(_ => {
          this.closeDialogHandle()
        }, 250)
      }
    },
    /**
     * 取消选择
     */
    cancel() {
      this.closeDialogHandle()
    },
    /**
     * 打开窗口
     */
    openDialog() {
      this.queryUsers()
      this.selection = [...this.selected]
    },
    /**
     * 关闭窗口
     */
    closeDialog() {
      this.$emit('update:show', false)
    },
    /**
     * 关闭窗口处理
     */
    closeDialogHandle() {
      this.searchUserForm = {
        pageNum: 1,
        pageSize: 10
      }
      this.selection = []
      this.visible = false
    },
    /*
    *  选中当前行
    * */
    rowClick(row) { // 单选时使用
      if (this.multi) return
      const valueAttr = this.props.value
      const labelAttr = this.props.label
      const result = {}
      result[valueAttr] = row.fid
      result[labelAttr] = row.ftype && row.ftype === 40 ? row.remark : row.nickName
      result.userName = row.userName
      this.selection = [result]
    },
    /**
     * 选择单个事件
     * @param selection
     * @param row 当前操作项
     */
    selectHandle(selection = [], row) {
      this.selectLoading = true
      const valueAttr = this.props.value
      const labelAttr = this.props.label
      const flag = selection.findIndex(item => item.fid === row.fid) > -1
      if (flag) {
        const result = {}
        result[valueAttr] = row.fid
        result[labelAttr] = row.ftype && row.ftype === 40 ? row.remark : row.nickName
        result.userName = row.userName
        this.selection.push(result)
      } else {
        const index = this.selection.findIndex(item => item[valueAttr] === row.fid)
        this.selection.splice(index, 1)
      }
    },
    /**
     * 选择全部事件
     * @param selection
     */
    selectAllHandle(selection = []) {
      const valueAttr = this.props.value
      const labelAttr = this.props.label
      const currentUserValues = this.list.map(item => item.fid)
      this.selection = this.selection.filter(item => !currentUserValues.includes(item[valueAttr]))
      if (selection.length > 0) {
        this.selection.push(...selection.map(item => {
          const result = {}
          result[valueAttr] = item.fid
          result[labelAttr] = item.remark || item.nickName
          result.userName = item.userName
          return result
        }))
      }
    },
    /**
     * 选择项改变事件
     * @param selection
     */
    selectionChangeHandle(selection = []) {
    },
    /**
     * 查询部门树
     */
    queryUsers() {
      const params = this.searchUserForm
      this.queryLoading = true
      listUser(params).then(res => {
        if (res.code === 200) {
          this.list = res.rows
          this.total = res.total
          const valueAttr = this.props.value
          this.$nextTick(() => {
            if (this.selection.length > 0) {
              const selectedValues = this.selection.map(item => item[valueAttr])
              this.list.forEach(item => {
                if (selectedValues.includes(item.fid)) {
                  this.$refs.table.toggleRowSelection(item)
                }
              })
            }
          })
        }
        this.queryLoading = false
      })
    },
    clearSearchForm() {
      this.searchUserForm = {
        pageNum: 1,
        pageSize: 10
      }
      this.queryUsers()
    }
  }
}
</script>

<style lang='scss' scoped>
  .show-selection {
    padding: 5px 0;
    .title {
      height: 30px;
      line-height: 30px;
    }
    .content {
      display: flex;
      justify-items: center;
      align-items: center;
      flex-wrap: wrap;
      .content-item {
        height: 30px;
        line-height: 30px;
        padding: 0 5px;
        cursor: pointer;
      }
    }
  }

</style>
